package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.constant.SourceType;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainManager;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 责任链管理者
 * @author lixu
 */
@Service
public class FilterChainManagerImpl implements FilterChainManager {

    //统一管理所有策略
    @Autowired
    private Map<String, FilterChainService> filterMap;//目前是长度 6个
    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public void executeFilter(StandardSubmit standardSubmit) {
        //1: 根据当前客户的ID查询此客户到底执行哪个策略
        Map map = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        //客户的剩余的钱
        // Object --> Integer  Object-->String  Object --> Long 类型强转异常
        standardSubmit.setFee(Long.parseLong((String) map.get("fee")));
        String filter = (String) map.get("filters");
        if(!StringUtils.isEmpty(filter)){
            //有策略   phase,black,limitFiveMinutes,dirtyWords,fee,router
            String[] filters = filter.split(",");
            for (String f : filters) {
                FilterChainService filterChainService = filterMap.get(f);
                if(filterChainService == null){
                    continue;
                }
                boolean strategy = filterChainService.strategy(standardSubmit);
                if(!strategy){
                    //失败了
                    standardSubmit.setErrorCode("10000");
                    //打印日志  发送消息到RabbitMQ
                    pushMsgUtil.sendLog(standardSubmit,"10000");
                    //判断必须是Http请求 有报告
                    if(SourceType.HTTP == standardSubmit.getSource()){
                        //记录报告  发送消息到RabbitMQ
                        pushMsgUtil.pushReport(standardSubmit,"10000");
                    }
                    break;//跳出当前for循环
                }
            }
            //啥事不干
        }
    }
}
